import pymssql
import qrcode
import docxtpl
import os,sys,pathlib
from docxtpl import DocxTemplate, InlineImage
from docx.shared import Mm, Inches, Pt
import jinja2
from jinja2.utils import Markup

savepath="c:\\pic\\"
tpl=DocxTemplate('c:\\pic\\inline_image_tpl.docx')
conn=pymssql.connect(host='172.16.2.139',user='sa',password='P@ssw0rd',database='THIS4',charset='cp936')
cursor=conn.cursor()
cursor.execute(
                """select idm,ypmc,ypgg,cjmc from YK_YPCDMLK    
                  where tybz=0 and yplh in ('01','02') 
                  order by fldm 
                """
                )
ypdata=cursor.fetchall()
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=21,
    border=4)


frameworks=[]
#生成模板数据
for idm,ypmc,ypgg,cjmc in ypdata:
    filename_img=savepath+str(idm)+'.jpg'
    frameworks.append({'image':InlineImage(tpl,filename_img,height=Mm(25)),'ypmc':ypmc,'ypgg':ypgg,'cjmc':cjmc})
    


#生成二维码
for i in range(len(ypdata)):
    qr.add_data(ypdata[i][0])
    
    qr.make(fit=True)
    img_file=savepath+str(ypdata[i][0])+'.jpg'
    
    img = qr.make_image()
    img.convert("RGBA")
    img.save(img_file)
    qr.clear()
    #print (ypdata[i][0],ypdata[i][1],ypdata[i][2],ypdata[i][3])



context = {
  

    'frameworks' : frameworks
    
}
# testing that it works also when autoescape has been forced to True
jinja_env = jinja2.Environment(autoescape=True)
tpl.render(context, jinja_env)
tpl.save('c:\\pic\\inline_image.docx')

